package com.ganyu.component;

import com.ganyu.domain.entity.Article;
import com.ganyu.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * DATA: 2022/9/27
 * Author: 晨夕
 * @Description 项目启动前将数据库中查询到的浏览量插入到redis中
 */
@Component
public class UpdateViewCountJob implements CommandLineRunner {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void run(String... args) throws Exception {
        //从数据库中查询浏览量
        List<Article> articles = articleMapper.selectList(null);
        HashMap<String, Integer> viewMap = new HashMap<>();
        for (Article article : articles){
            viewMap.put(article.getId().toString(),article.getViewCount().intValue());
        }
        //将数据插入到redis中
        redisCache.setCacheMap("article:viewCount",viewMap);
    }
}
